package com.ruoyi.wx.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.PermissionService;
import com.ruoyi.wx.entity.PtClassExpAll;
import com.ruoyi.wx.entity.vo.ChooseExpVo;
import com.ruoyi.wx.service.IPtClassExpAllService;
import com.ruoyi.wx.service.IPtExpService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 班级本学期要做的全部实验 前端控制器
 * </p>
 *
 * @author moxiu
 * @since 2022-03-04
 */
@RestController
@Api(value = "班级实验接口", tags = {"班级实验接口测试"})
@RequestMapping("/wx")
public class PtClassExpAllController {

    @Autowired
    private IPtClassExpAllService ptClassExpAllService;

    @Autowired
    private IPtExpService ptExpService;

    @Autowired
    private PermissionService permissionService;


    @ApiOperation("给班级选择本学期要做的全部实验")
    @PostMapping("/chooseExp")
    public AjaxResult<Void> chooseExp(@Validated @RequestBody ChooseExpVo chooseExpVo) {
        if (!permissionService.hasTeacherOrAdmin()) {
            return AjaxResult.error("没有权限");
        }
        PtClassExpAll ptClassExpAll = new PtClassExpAll();
        ptClassExpAll.setClassId(chooseExpVo.getClassId());
        Long[] expId = chooseExpVo.getExpId();
        Set<Long> set = new HashSet<>(Arrays.asList(expId));
        ptClassExpAll.setExpList(JsonUtils.toJsonString(set));
        boolean b = ptClassExpAllService.saveOrUpdate(ptClassExpAll, Wrappers.lambdaUpdate(PtClassExpAll.class)
            .eq(PtClassExpAll::getClassId, ptClassExpAll.getClassId())
        );
        return b ? AjaxResult.success() : AjaxResult.error();
    }

    @ApiOperation("查看自己要做的全部实验")
    @GetMapping("/myExpAll")
    public AjaxResult myExpAll() {
        Long deptId = SecurityUtils.getDeptId();

        if (deptId == null) {
            return AjaxResult.error("未选择班级！");
        }

        PtClassExpAll one = ptClassExpAllService.getOne(Wrappers.lambdaQuery(PtClassExpAll.class)
            .eq(PtClassExpAll::getClassId, deptId)
            .select(PtClassExpAll::getExpList)
        );

        if (one.getExpList() == null) {
            return AjaxResult.error("等待老师选择实验");
        }
        List<Integer> list = (List<Integer>) JSONObject.parse(one.getExpList());

        long[] l = new long[list.size()];
        for (int i = 0; i < list.size(); i++) {
            l[i] = list.get(i);
        }

        return AjaxResult.success(ptExpService.getExpByList(l));
    }

}
